<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 公司接口
 */
class Company extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Company();
    }

    public function otherdata()
    {

        $industry = $this->model->getIndustryList();
//        $industry = one_array_two($industry);

        $industry = array_values($industry);
        $data = [

            'goods_showtype' => $this->model->getGoodsShowtypeList(),
            'status' => $this->model->getStatusList(),
            'is_vip' => $this->model->getIsVipList(),
            'industry' => $industry
        ];

        $this->success('', $data);
    }

    /**
     * 添加
     */
    public function add()
    {
        $userinfo = $this->auth->getUserinfo();
        $company = \think\Db::name('company')->where(['creator' => $this->auth->id])->find();
        if ($company) $this->error('您已创建过公司');
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['creator'] = $this->auth->id;
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('公司创建成功,请等待审核');
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

    }

    /**
     * 详情
     */
    public function detail($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $this->success('', $row);
    }

    /**
     * $ids 公司id
     * 团队
     */
    public function team()
    {
        $user = $this->auth->getUserinfo();
        $id = $user['company_id'];
        $row = $this->model->get($id);
        if (!$row)
            $this->error(__('No Results were found'));

        $totalCustomer = Db::name('customer')->where(['company_id' => $id])->count();
        $successCustomer = Db::name('customer')->where(['company_id' => $id, 'status' => 10])->count();
        $totalCustomer - 1 >= 0 ? $chengjiaolv = number_format($successCustomer / $totalCustomer * 100, 2)
            : $chengjiaolv = 0;

        $kehutongji = [
            'totalCustomer' => $totalCustomer,
            'successCustomer' => $successCustomer,
            'rate' => $chengjiaolv
        ];
        $mouthTarget = Db::name('user')->where(['company_id' => $id, 'status' => 'normal'])->sum('mouth_target');
        $finishTarget = Db::name('user')->where(['company_id' => $id, 'status' => 'normal'])->sum('finish_target');
        $mouthTarget - 1 >= 0 ? $targetRate = number_format($finishTarget / $mouthTarget * 100, 2) : $targetRate = 0;

        $yejitongji = [
            'mouthTarget' => $mouthTarget,
            'finishTarget' => $finishTarget,
            'targetRate' => $targetRate
        ];
        $teamUserData = \app\common\model\User::getUserByCompanyId($id);
        $data = [
            'row' => $row,
            'kehutongji' => $kehutongji,
            'yejitongji' => $yejitongji,
            'teamUserCount' => $teamUserData['count'],
            'teamUserList' => $teamUserData['list'],
            'userinfo' => $user
        ];
        $this->success('', $data);
    }

    /**
     * 退出团队
     */
    public function leaveTeam()
    {
        $companyName = $this->request->request('company_name');
        $user = $this->auth->getUserinfo();
        $company = $this->model->get($user['company_id']);
        if ($company['name'] != $companyName) $this->error('团队名称错误');
        $selfCompanyInfo = Db::name('company')->where(['creator' => $this->auth->id])->find();
        if(empty($selfCompanyInfo)) $this->error('完善公司信息后才能退出团队');
        $selfCompanyId = $selfCompanyInfo['id'];
        //退出团队，独占客户转为共享
        Db::startTrans();
        try {
            Db::name('user')->where('id', $this->auth->id)->update(['company_id' => $user['selfcompany_id']]);
            Db::name('customer')->where(['user_id' => $this->auth->id])->update(['scope' => '1']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 解散团队
     */
    public function dismiss(){
        $companyName = $this->request->request('company_name');
        $user = $this->auth->getUserinfo();
        if(!$user['company_id']) $this->error('您没有加入团队');
        $company = $this->model->get($user['company_id']);
        if($companyName != $company['name']) $this->error('团队名称错误');
        if($company['creator'] != $this->auth->id) $this->error('您没有权限解散团队');
        \app\common\model\Company::dismiss($this->auth->id,$user['company_id']);
        $this->success('解散成功');
    }

    /**
     * 踢人
     */
    public function delSomeOne(){
        $userId = $this->request->request('user_id'); //被踢人用户id
        $user = $this->auth->getUserinfo();
        $company = $this->model->get($user['company_id']);
        if($company['creator'] != $this->auth->id) $this->error('您没有权限踢人');
        $res = Db::name('user')->where(['id' =>$userId,'company_id' => $user['company_id']])->update(['company_id' => 0,'is_access' => '1']);
        if($res !== false){
            $this->success('踢人成功');
        }else{
            $this->error('踢人失败');
        }

    }

    /**
     * 设置团队成员本月目标
     */
    public function setMouthTarget(){
        $user_id = $this->request->request('user_id/d');
        $account = $this->request->request('account/d');
        $user = $this->auth->getUserinfo();
        $company = $this->model->get($user['company_id']);
        if($company['creator'] != $this->auth->id) $this->error('您没有权限设置目标');

        $res = Db::name('user')->where('id',$user_id)->update(['mouth_target' => $account]);
        if($res !== false){
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }
    }



}